import {addPmGroup, selectAllProgressTem} from '@/api/evalutaion'
import Evaluation from '@/components/others/evalutaion'
import {useLoading} from '@/hooks/loading'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {defineComponent, reactive, watch, onMounted, onUnmounted} from 'vue'
const {message} = ant_design_vue

export default defineComponent({
  setup(props, ctx) {
    const {router} = useGlobalAPI()
    const {loading, startLoading, closeLoading} = useLoading()

    let state = reactive<{
      evalutaion: Evaluation.AddEvalutaionData
      reloadTime: NodeJS.Timeout | undefined
    }>({
      evalutaion: {
        /**考核表名称 */
        pmGroupName: '',
        appointScoreSwitch: 0,
        /**周期类型code */
        pmPeriodCode: '0025',
        /**考核组备注 */
        pmGroupDesc: '',
        /**周期类型名称 */
        pmPeriodName: '月度',
        /**考核组人员列表 */
        pmGroupUserList: [
          // {
          //   pmGroupUserDDId: '1618391431999590',
          //   pmGroupUserName: '魏东'
          // }
          // {
          //   pmGroupUserDDId: '233030103920321018',
          //   pmGroupUserName: '余志高'
          // }
          // {
          //   pmGroupUserDDId: '38424845683478',
          //   pmGroupUserName: '包伟方'
          // }
        ],
        /**考核组部门列表 */
        pmGroupDeptList: [
          // {
          //   pmGroupDeptDDId: '598431022',
          //   pmGroupDeptName: '信息化软件部'
          // }
        ],
        /**考核组绩效列表 */
        pmGroupDimensionList: [],
        /**考核组流程列表 */
        pmGroupProgressList: [],

        pmGroupExcUserList: []
      },
      reloadTime: undefined
    })

    /**监听考核表内容变化 state.evalutaion */
    watch(
      () => state.evalutaion,
      n => {
        console.log('添加考评组 考评组数据变化', n)
      },
      {deep: true}
    )

    function getProcessTems() {
      startLoading()
      selectAllProgressTem()
        .then(res => {
          state.evalutaion.pmGroupProgressList = combPmGroupProgressListByProgressTem(res.data)
          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    function combPmGroupProgressListByProgressTem(
      data: Evaluation.Progress[]
    ): Evaluation.PmGroupProgress[] {
      return data.map(item => ({
        pmGroupProgressId: item.pmGroupProgressTemId,
        pmGroupId: -1,
        pmGroupProgressName: item.pmGroupProgressTemName,
        pmGroupProgressStatus: item.pmGroupProgressTemStatus,
        pmGroupStageCode: item.pmGroupStageCode,
        isMakeProgress: item.isMakeProgress,
        sort: item.sort,
        pmProgressSetList: combPmProgressSetListByProgressTem(item.pmProgressSetTemList)
      }))
    }

    function combPmProgressSetListByProgressTem(
      data: Evaluation.PmProgressSetTem[]
    ): Evaluation.PmProgressSet[] {
      if (!data) return []
      return data.map(item => ({
        pmGroupProgressSetId: item.pmGroupProgressSetTemId,
        pmGroupProgressId: -1,
        pmGroupProgressSetName: item.pmGroupProgressSetTemName,
        pmGroupProgressSetEngName: item.pmGroupProgressSetTemEngName,
        sort: item.sort,
        parentId: item.parentId,
        pmGroupProgressSetValue: item.pmGroupProgressSetTemValue,
        pmGroupProgressSetTemAdditionalValue: item.pmGroupProgressSetTemAdditionalValue,
        pmGroupProgressSetList:
          !item.pmGroupProgressSetTemList || !item.pmGroupProgressSetTemList.length
            ? []
            : combPmProgressSetListByProgressTem(item.pmGroupProgressSetTemList)
      }))
    }

    function handleConfirm() {
      if (!state.evalutaion.pmGroupName) {
        message.warning({
          content: '请输入考评组名称'
        })
        return
      }

      if (!state.evalutaion.pmGroupDeptList.length && !state.evalutaion.pmGroupUserList.length) {
        message.warning({
          content: '请选择考评员工'
        })
        return
      }

      if (!state.evalutaion.pmGroupDimensionList.length) {
        message.warning({
          content: '模板指标中的维度为空！'
        })
        return
      }

      for (let i = 0; i < state.evalutaion.pmGroupProgressList.length; i++) {
        const pmGroupProgress = state.evalutaion.pmGroupProgressList[i]

        if (
          pmGroupProgress.pmGroupStageCode === '0017' ||
          pmGroupProgress.pmGroupStageCode === '0018'
        ) {
          if (pmGroupProgress.pmProgressSetList) {
            for (let ii = 0; ii < pmGroupProgress.pmProgressSetList.length; ii++) {
              const pmProgressSet = pmGroupProgress.pmProgressSetList[ii]
              if (
                pmProgressSet.pmGroupProgressSetEngName === 'confirmUser' ||
                pmProgressSet.pmGroupProgressSetEngName === 'scoreUser'
              ) {
                if (pmProgressSet.pmGroupProgressSetList) {
                  for (let iii = 0; iii < pmProgressSet.pmGroupProgressSetList.length; iii++) {
                    const pmGroupProgressSet = pmProgressSet.pmGroupProgressSetList[iii]
                    if (pmGroupProgressSet.pmGroupProgressSetValue === '1') {
                      switch (pmProgressSet.pmGroupProgressSetEngName) {
                        case 'confirmUser':
                          break
                        case 'scoreUser':
                          switch (pmGroupProgressSet.pmGroupProgressSetEngName) {
                            case 'scoreAppointEmployee':
                              if (pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue) {
                                let userInfoList =
                                  pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue.split(';')

                                for (let j = 0; j < userInfoList.length; j++) {
                                  const userInfo = userInfoList[j].split(',')[0]

                                  let userWeight = Number(userInfoList[j].split(',')[1])

                                  if (!userWeight || userWeight !== userWeight) {
                                    message.warning(
                                      '给指定评分人：' + userInfo.split('-')[1] + ', 没有输入权重'
                                    )
                                    return
                                  }
                                }
                              } else {
                                message.warning('考评流程中上级评分的指定人员未选择')
                                return
                              }
                              break
                            case 'scoreLeader':
                              if (pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue) {
                                let userInfoList =
                                  pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue.split(';')

                                for (let j = 0; j < userInfoList.length; j++) {
                                  const leader = userInfoList[j].split(',')[0]

                                  let leaderWeight = Number(userInfoList[j].split(',')[1])

                                  if (!leaderWeight || leaderWeight !== leaderWeight) {
                                    message.warning(
                                      (leader == '1' ? '直属主管' : leader + '级主管') +
                                        '没有输入权重'
                                    )
                                    return
                                  }
                                }
                              } else {
                                message.warning('考评流程中上级评分的主管未选择')
                                return
                              }
                              break
                            default:
                              break
                          }
                          break
                        default:
                          break
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      // 添加维度-指标的自评模板字段名
      // state.evalutaion.pmGroupDimensionList.forEach((item1, index1) => {
      //   item1.pmGroupDimensionTargetList.forEach((item2, index2) => {
      //     item2.pmGroupDimensionSelfContentTem = item2.selfContentTem
      //     delete item2.selfContentTem
      //   })
      // })

      console.log('考评组数据add', state.evalutaion)

      startLoading()
      addPmGroup(state.evalutaion)
        .then(res => {
          const timer = setTimeout(() => {
            closeLoading()
            router.back()
          }, 500)
          state.reloadTime = timer
        })
        .catch(err => {
          closeLoading()
        })
    }

    onMounted(() => {
      getProcessTems()
    })

    onUnmounted(() => {
      // @ts-ignore
      state.reloadTime && clearTimeout(state.reloadTime)
    })

    return () => (
      <Evaluation
        title='添加考评组'
        v-model={[state.evalutaion, 'evalutaion']}
        onConfirm={handleConfirm}
        loading={loading.value}
        showAppointScore={false}
      ></Evaluation>
    )
  }
})
